import geopandas as gpd
from utils.simutils import gen_matchrelation,process_df,cosine_sim,merging_line,merging_CCline,LCSS_sim,ge_curvesTO,ge_curvesTC,ge_curvesTT
import pandas as pd
import numpy as np
import time

start_time = time.time()



# 定义几何类型匹配逻辑
#每个未找到联合合并线，可以让他直接为0
def calculate_similarity(row, contour1, contour2):
    # 获取匹配的几何对象
    g1 = contour1[contour1['myid'] == row['col1']].iloc[0]
    g2 = contour2[contour2['myid'] == row['col2']].iloc[0]
    # print(g1.myid)
    # print(g2.myid)
    # 提取几何分类
    gcla1 = g1['gcla']
    gcla2 = g2['gcla']

    ### 根据分类计算相似度和匹配类别

    if gcla1 == 1 and gcla2 == 1:
        sim = cosine_sim(g1, g2)
        FF = 1
    ###开放-闭合    
    elif (gcla1 == 1 and gcla2 == 2) or (gcla1 == 2 and gcla2 == 1):
        
        contour = contour2 if gcla1 == 1 else contour1
        g_main = g2 if gcla1 == 1 else g1 #闭合
        g_other = g1 if gcla1 == 1 else g2  
        ch_g2 = g_other.geometry.convex_hull
        if ch_g2.intersects(g_main.geometry):
            line1, line2 = merging_line(contour, g_main, g_other)
            if line1 == g_main.geometry and line2 == g_other.geometry:
                #未找到联合合并线           
                sim=cosine_sim(g1, g2)
                FF = 1
            else:
                sim = LCSS_sim(line1, line2) 
                FF = 2
        else:
            sim=0
            FF = 0
            # mgc = 2.11
# 闭合-闭合      
    elif gcla1 == 2 and gcla2 == 2:
        
        # 增加空间相交条件
        ch_g1 = g1.geometry.convex_hull
        ch_g2 = g2.geometry.convex_hull
        if ch_g1.intersects(ch_g2):
            sim = cosine_sim(g1, g2)
            FF = 1
            if sim<0.9332:#依据区域进行更新#HG=0.7639；Clf=0.9332
                # 计算面积比例
                area_ratio = g1.geometry.convex_hull.area / g2.geometry.convex_hull.area
                #g2比较大
                if area_ratio <= 1:
                    line1, line2 = merging_CCline(contour1, g1, g2)
                    if line2 == g2.geometry and line1 == g1.geometry:
                        sim=cosine_sim(g1, g2)
                        FF = 1
                    else:
                        sim = LCSS_sim(line1, line2)
                        FF = 2
                #g1比较大    
                elif area_ratio > 1:
                    line1, line2 = merging_CCline(contour2, g2, g1)
                    if line1 == g2.geometry and line2 == g1.geometry:
                        sim=cosine_sim(g1, g2)
                        FF = 1
                    else:
                        sim = LCSS_sim(line1, line2)
                        FF = 2 
        else:
             sim=0
             FF = 0
            #  mgc = 4.11

    ### 开放-截断、截断-截断
    elif (gcla1 == 1 and gcla2 == 3) or (gcla1 == 3 and gcla2 == 1):
        if gcla1 == 3:
            seg1, seg2 = ge_curvesTO(g1, g2)

        else:
            seg1, seg2 = ge_curvesTO(g2, g1)
        sim = cosine_sim(seg1.iloc[0], seg2.iloc[0])        
        FF = 1
    elif gcla1 == 3 and gcla2 == 3:
        
        seg1, seg2 = ge_curvesTT(g1, g2)
        sim = cosine_sim(seg1.iloc[0], seg2.iloc[0])
        FF = 1
    
                             
    # 闭合-截断
    elif (gcla1 == 2 and gcla2 == 3) or (gcla1 == 3 and gcla2 == 2):
        contour = contour1 if gcla1 == 2 else contour2
        g_main = g1 if gcla1 == 2 else g2 #闭合线
        g_other = g2 if gcla1 == 2 else g1
        

        if g_main.geometry.length <= g_other.geometry.length:
            
            # 增加空间约束
            ch_g2 = g_other.geometry.convex_hull
            if ch_g2.intersects(g_main.geometry):
                line1, line2 = merging_line(contour, g_main, g_other)
                if line1 == g_main.geometry and line2 == g_other.geometry:
                    #未找到联合合并线           
                    sim=cosine_sim(g1, g2)
                    FF = 1
                else:
                    sim = LCSS_sim(line1, line2) 
                    FF = 2
            else:

                sim=0
                FF = 0
                      
        else:
            seg1, seg2 = ge_curvesTC(g_other, g_main)
            sim = cosine_sim(seg1.iloc[0], seg2.iloc[0])
            FF = 1

    return sim, FF 

####################################################################

""" 主函数 """
# 读入数据
# #加利福尼亚
contour1 = gpd.read_file('E:/Data/QGIS/2contour/Calif/ClfUg_Ct.shp' ,encoding='gbk')
contour2= gpd.read_file('E:/Data/QGIS/2contour/Calif/ClfDem_Ct.shp' ,encoding='gbk')
# # 香港
# contour1 = gpd.read_file('E:/Data/QGIS/2contour/HG/HG2W_CtG.shp' ,encoding='gbk')
# contour2= gpd.read_file('E:/Data/QGIS/2contour/HG/HGDEM_CtG.shp' ,encoding='gbk')

# # # 生成匹配关系，基于缓存区距离HG=49.11，Clf=21.03
# match_df1 = gen_matchrelation(contour2, contour1, 21.03,"ele",overlap_threshold=0.01)
# match_df0=process_df(match_df1 )
# # 生成真实匹配标记 
# true_pairs = pd.read_csv('data/ClfMR_T.csv', header=0)

# valid_pairs = set(zip(
#     true_pairs['col1'].astype(str), 
#     true_pairs['col2'].astype(str)
# ))
# col1 = match_df0['col1'].astype(str).values
# col2 = match_df0['col2'].astype(str).values
# match_df0['Ture'] = np.where([(c1, c2) in valid_pairs for c1, c2 in zip(col1, col2)], 1, 0)
# match_df0.to_csv('data/Clf_FMR.csv',index=False)
match_df0 = pd.read_csv('data/Clf_FMR.csv')


# 遍历匹配关系并计算相似度
for idx, row in match_df0.iterrows():
    sim, mgc = calculate_similarity(row, contour1, contour2)
    match_df0.at[idx, 'sim'] = sim
    match_df0.at[idx, 'FF'] = mgc


# 保存结果到CSV文件
match_df0.to_csv('data/ClfSim_mn1.csv', index=False)

print(f"总执行时间: {time.time()-start_time:.2f}秒")
